<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\BankCard as BankCardModel;
use app\payment\model\Download as DownloadModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 银行卡设置控制器
 */
class BankCard extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'see', 'add', 'edit', 'export'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->add_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['edit'])) {
            if (!$this->edit_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['bank_card' => '收款银行卡', 'name' => '收款人姓名', 'merchant_id' => '商户号', 'status' => '状态'];

        // 获取查询条件
        $map = $this->getMap();

        if ($this->no_auth) {
            $map[] = ['merchant_id', 'eq', $this->merchant_id];
            unset($search['merchant_id']);
        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = BankCardModel::where($map)->order('create_time desc')->paginate($list_rows);
        // 分页数据
        $page = $data_list->render();

        $status_type = $this->role > $this->have_auth ? 'status' : 'switch';
        $items = [
            ['id', 'ID'],
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['name', '收款人姓名'],
            ['bank_card', '收款银行卡'],
            ['account_opening_branch', '开户支行'],
            ['mobile', '收款人手机号'],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', $status_type],
            ['right_button', '操作', 'btn']
        ];

        $hideCheckbox = false;
        if ($this->no_auth) {
            unset($items[1]);
            $hideCheckbox = true;
        }

        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-md btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox($hideCheckbox)
            ->setPageTitle('银行卡设置') // 设置页面标题
            ->setTableName('payment_bank_card') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addTopButton('export', $export) // 添加按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        $count = BankCardModel::where($map)->order('id desc')->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }

        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "银行卡导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败！");
        }

        $field = [
            'merchant_id',
            'bank_type',
            'bank_name',
            'name',
            'id_card',
            'mobile',
            'bank_card',
            'account_type',
            'account_opening_branch',
            'couplet_number',
            'province',
            'city',
            'status',
            'create_time',
            'update_time',
        ];

        $cellName = [
            '商户号',
            '银行卡类型',
            '收款银行名称',
            '收款人姓名',
            '收款人身份证',
            '收款人手机号',
            '收款银行卡',
            '账户类型',
            '开户支行',
            '联行号',
            '省份名称',
            '城市名称',
            '状态',
            '创建时间',
            '更新时间',
        ];

        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_bank_card')
            ->where($map)
            ->field($field)
            ->chunk(100, function ($all) use ($fp) {
                foreach ($all as $single) {

                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = date('Y-m-d H:i:s', $single['update_time']);
                    $single['status'] = $single['status'] ? '开启' : '禁用';

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'create_time', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        $max_bank_card_count = pay_config('max_bank_card_count');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }

            $bank_card_count = BankCardModel::where(['merchant_id' => $data['merchant_id']])->count();

            if ($bank_card_count >= $max_bank_card_count) {
                $this->error("每个商户最多绑定{$max_bank_card_count}个银行卡！", url('index'));
            }

            // 验证
            $result = $this->validate($data, 'BankCard');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            $info = BankCardModel::where('id', $data['id'])->find();
            if ($info) {
                $this->error("请刷新，数据已经存在！");
            }

            if ($temp = BankCardModel::create($data)) {
                // 记录行为
                action_log('payment_bank_card_add', 'bank_card', $temp['id'], UID, json_encode($temp));
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }

        $id = date('YmdHis');

        $items = [
            ['hidden', 'id', $id],
            ['select', 'merchant_id', '商户号', '', all_merchant()],
            ['select', 'bank_type', '银行卡类型', '', ['借记卡' => '借记卡', '信用卡' => '信用卡', '贷记卡' => '贷记卡']],
            ['text', 'bank_name', '收款银行名称', '必填：比如:<code>中国工商银行</code>'],
            ['text', 'name', '收款人姓名', '必填：比如:<code>我是谁</code>'],
            ['text', 'id_card', '收款人身份证', '必填：不清楚填0<code>身份证号码</code>'],
            ['text', 'mobile', '收款人手机号', '可填：比如:<code>13888888888</code>说明：如果填写，提现成功此手机号可能收到短信。'],
            ['text', 'bank_card', '收款银行卡', '必填：比如:<code>6217002870051515888</code>'],
            ['text', 'bank_card_confirm', '确认收款银行卡', '必填：比如:<code>6217002870051515888</code>'],
            ['radio', 'account_type', '账户类型', '', ['私户' => '私户', '公户' => '公户'], '私户'],
            ['text', 'account_opening_branch', '开户支行', '必填：比如:<code>工商银行广州高新支行</code>'],
            ['text', 'couplet_number', '联行号', '<code>公户</code>账户必须填写：比如:<code>103521003839</code>：<a target="_blank" href="https://www.hebbank.com/corporbank/otherBankQueryWeb.do">查看地址</a>'],
            ['text', 'province', '省份名称', '必填：比如:<code>广东省</code>'],
            ['text', 'city', '城市名称', '必填：比如:<code>广州市</code>'],
            ['textarea', 'merchant_remark', '商户备注'],
            ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        if ($this->role > $this->have_auth) {
            unset($items[1]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips("绑定银行卡，方便提现使用，系统设置每个商户最多绑定{$max_bank_card_count}个银行卡")
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = BankCardModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'bank_type', '银行卡类型', '', ['借记卡' => '借记卡', '信用卡' => '信用卡', '贷记卡' => '贷记卡']],
            ['static', 'bank_name', '收款银行名称'],
            ['static', 'name', '收款人姓名'],
            ['static', 'id_card', '收款人身份证'],
            ['static', 'mobile', '收款人手机号'],
            ['static', 'bank_card', '收款银行卡'],
            ['static', 'account_type', '账户类型', '', ['私户' => '私户', '公户' => '公户'], '私户'],
            ['static', 'account_opening_branch', '开户支行'],
            ['static', 'couplet_number', '联行号'],
            ['static', 'province', '省份名称'],
            ['static', 'city', '城市名称'],
            ['textarea', 'merchant_remark', '备注[:无]', '', '', 'disabled', ''],
            ['radio', 'status', '状态', '', ['禁用', '启用'], '', '', 'disabled', ''],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id  id
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }
            // 验证
            $result = $this->validate($data, 'BankCard');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }

            if (BankCardModel::update($data)) {
                $temp = BankCardModel::where('id', $data['id'])->find();
                // 记录行为
                action_log('payment_bank_card_edit', 'bank_card', $temp['id'], UID, json_encode($temp));
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = BankCardModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        $items = [
            ['hidden', 'id'],
            ['select', 'merchant_id', '商户号', '', all_merchant()],
            ['select', 'bank_type', '银行卡类型', '', ['借记卡' => '借记卡', '信用卡' => '信用卡', '贷记卡' => '贷记卡']],
            ['text', 'bank_name', '收款银行名称', '必填：比如:<code>中国工商银行</code>'],
            ['text', 'name', '收款人姓名', '必填：比如:<code>我是谁</code>'],
            ['text', 'id_card', '收款人身份证', '必填：<code>身份证号码</code>'],
            ['text', 'mobile', '收款人手机号', '可填：比如:<code>13888888888</code>说明：如果填写，提现成功此手机号可能收到短信。'],
            ['text', 'bank_card', '收款银行卡', '必填：比如:<code>6217002870051515888</code>'],
            ['text', 'bank_card_confirm', '确认收款银行卡', '必填：比如:<code>6217002870051515888</code>'],
            ['radio', 'account_type', '账户类型', '', ['私户' => '私户', '公户' => '公户'], '私户'],
            ['text', 'account_opening_branch', '开户支行', '必填：比如:<code>工商银行广州高新支行</code>'],
            ['text', 'couplet_number', '联行号', '<code>公户</code>账户必须填写：比如:<code>103521003839</code>：<a target="_blank" href="https://www.hebbank.com/corporbank/otherBankQueryWeb.do">查看地址</a>'],
            ['text', 'province', '省份名称', '必填：比如:<code>广东省</code>'],
            ['text', 'city', '城市名称', '必填：比如:<code>广州市</code>'],
            ['textarea', 'merchant_remark', '备注'],
            ['radio', 'status', '状态', '', ['禁用', '启用']],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        if ($this->role > $this->have_auth) {
            unset($items[1]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = BankCardModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['payment_bank_card_' . $type, 'payment_bank_card', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = BankCardModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['payment_bank_card_edit', 'payment_bank_card', $id, UID, $details]);
    }
}
